package ui.custom.table;

import java.lang.reflect.Field;

import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.Item;

import type.TableLabelProviderObject;

public class CellModifier implements ICellModifier {
	private TableViewer tv;
	public CellModifier(TableViewer tv) {
		this.tv = tv;
	}

	/**
	 * Returns whether the property can be modified
	 * 
	 * @param element
	 *            the element
	 * @param property
	 *            the property
	 * @return boolean
	 */
	public boolean canModify(Object element, String property) {
		TableLabelProviderObject obj = (TableLabelProviderObject) element;
		Object[] props = tv.getColumnProperties();
		int index=-1;
		for (int i = 0; i < props.length; i++) {
			if(props[i].toString().equals(property)){
				index = i;
				break;
			}
		}
		return obj.alloweModify(index);
	}

	/**
	 * Returns the value for the property
	 * 
	 * @param element
	 *            the element
	 * @param property
	 *            the property
	 * @return Object
	 */
	public Object getValue(Object element, String property) {
		TableLabelProviderObject obj = (TableLabelProviderObject) element;
		String fieldName = property;
		try {
			Field f = obj.getClass().getDeclaredField(fieldName);
			f.setAccessible(true);
			Object o = f.get(obj);
			return o!=null?o.toString():"";
		} catch (SecurityException e) {
			e.printStackTrace();
		}  catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Modifies the element
	 * 
	 * @param element
	 *            the element
	 * @param property
	 *            the property
	 * @param value
	 *            the value
	 */
	public void modify(Object element, String property, Object value) {
		if (element instanceof Item)
			element = ((Item) element).getData();
		TableLabelProviderObject obj = (TableLabelProviderObject) element;
		String fieldName = property;
		try {
			Field f = obj.getClass().getDeclaredField(fieldName);
			f.setAccessible(true);
			f.set(obj, value);
		} catch (SecurityException e) {
			e.printStackTrace();
		}  catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
		tv.refresh();
	}

}
